<template>
  <div>
    <van-nav-bar title="银行卡">
      <img
        src="~assets/image/arrow_left.png"
        alt=""
        slot="left"
        width="20"
        height="20"
        @click="leftClick"
      />
    </van-nav-bar>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-tabs
        v-model="active"
        line-width="50%"
        title-active-color="#ee0a24"
        title-inactive-userNamecolor="#666"
        @click="tabsAddBank"
      >
        <!-- 信用卡 -->
        <van-tab title="信用卡">
          <div v-if="getCreditCardflag">
            <div
              class="bank"
              v-for="item in CreditCardList"
              :key="item.id"
              :style="
                'background:' + (item.background ? item.background : '#272727')
              "
            >
              <div class="bank-main">
                <van-image
                  v-if="item.bank_acronym"
                  round
                  width="50"
                  height="50"
                  :src="
                    require('../../assets/image/bankIcon/BANK_' +
                      item.bank_acronym +
                      '.png')
                  "
                />
                <van-image
                  v-else
                  round
                  width="50"
                  height="50"
                  src="../../assets/image/bankIcon/BANK_default.png"
                />

                <div class="bankCrad">
                  <div class="bank_name">
                    {{ item.bankName }}
                    <span>( {{ item.userName | getFirstName }} )</span>
                  </div>
                  <p class="bank-type">充值卡</p>
                  <p class="bankCradId">{{ item.cardNo | getCrad }}</p>
                </div>
                <p v-if="item.idDef == 1">默认卡</p>
                <p v-else class="setCradka" @click="updataMoRen(item)">
                  设为默认卡
                </p>
              </div>
              <div class="bank-up">
                <p>{{ item.cardType }}</p>
                <div @click="UpdateCard(item)">
                  <img
                    src="~assets/image/bank_update.png"
                    width="20"
                    height="20"
                    alt=""
                  />
                  修改
                </div>
                <div @click="delCredClick(item)">
                  <img
                    src="~assets/image/bank_del.png"
                    width="20"
                    height="20"
                    alt=""
                  />
                  删除
                </div>
              </div>
            </div>
          </div>
          <van-empty v-else image-size="120px">
            <img slot="image" src="~assets/image/img_credit.png" />
            <div slot="default">
              <p>添加信用卡</p>
              <p>开始制定还款计划吧</p>
              <p>全额还款一键即可轻松搞定</p>
            </div>
            <p class="addCredit" @click="AddCreditCard">添加信用卡</p>
          </van-empty>
        </van-tab>
        <!-- end 信用卡 -->
        <!-- 储蓄卡 -->
        <van-tab title="储蓄卡">
          <div v-if="getStorageCardflag">
            <div v-if="getCreditCardflag">
              <div
                class="bank"
                v-for="item in StorageCardList"
                :key="item.id"
                :style="
                  'background:' +
                  (item.background ? item.background : '#272727')
                "
              >
                <div class="bank-main">
                  <van-image
                    v-if="item.bank_acronym"
                    round
                    width="50"
                    height="50"
                    :src="
                      require('../../assets/image/bankIcon/BANK_' +
                        item.bank_acronym +
                        '.png')
                    "
                  />
                  <van-image
                    v-else
                    round
                    width="50"
                    height="50"
                    src="../../assets/image/bankIcon/BANK_default.png"
                  />
                  <div class="bankCrad">
                    <div class="bank_name">
                      {{ item.bankName }}
                      <span>( {{ item.userName | getFirstName }} )</span>
                    </div>
                    <p class="bank-type">提现卡</p>
                    <p class="bankCradId">{{ item.cardNo | getCrad }}</p>
                  </div>
                  <p v-if="item.idDef == 1">默认卡</p>
                  <p v-else class="setCradka" @click="updataMoRen(item)">
                    设为默认卡
                  </p>
                </div>
                <div class="bank-up">
                  <p>{{ item.cardType }}</p>
                  <div @click="UpdateModificationCard(item)">
                    <img
                      src="~assets/image/bank_update.png"
                      width="20"
                      height="20"
                      alt=""
                    />
                    修改
                  </div>
                  <div @click="delStoragCredClick(item)">
                    <img
                      src="~assets/image/bank_del.png"
                      width="20"
                      height="20"
                      alt=""
                    />
                    删除
                  </div>
                </div>
              </div>
            </div>
          </div>
          <van-empty v-else image-size="120px">
            <img slot="image" src="~assets/image/img_credit.png" />
            <div slot="default">
              <p>添加储蓄卡</p>
              <p>开始制定还款计划吧</p>
              <p>全额还款一键即可轻松搞定</p>
            </div>
            <p class="addCredit" @click="AddStorageCard">添加储蓄卡</p>
          </van-empty>
        </van-tab>
        <!--end 储蓄卡 -->
      </van-tabs>
    </van-pull-refresh>
    <div class="footer" @click="addBank">
      <img
        src="../../assets/image/add_bank.png"
        width="20"
        height="20"
        alt=""
      />
      <span>添加银行卡</span>
    </div>
  </div>
</template>
<script>
import {
  queryAllBankCardInfoApi,
  queryCardPicApi,
  queryDelBankCrad,
  queryModifyDefaultWithdrawalsCardInfoApi,
} from "network/ApiServe";

export default {
  filters: {
    getFirstName(name) {
      let names = "";
      if (name.length == 2) {
        names = name.substring(0, 1) + "*";
      } else {
        for (let i = 0; i < name.length; i++) {
          if (i == 0) {
            names = name[i];
          }
          if (name.length - 1 - i == 0) {
            names += name[i];
          }
          if (i > 0 && i < name.length - 1) {
            names += "*";
          }
        }
      }
      return names;
    },
    getCrad(name) {
      let names = "";

      for (let i = 0; i < name.length; i++) {
        if (i < 2) {
          names += name[i];
        }
        if (name.length - 1 - i <= 1) {
          names += name[i];
        }
        if (i > 0 && i < name.length - 2) {
          names += "*";
        }
      }

      return names;
    },
  },
  created() {
    this.token = localStorage.getItem("token");
    this.userId = localStorage.getItem("userId");
  },
  computed: {
    getCreditCardflag() {
      if (this.CreditCardList.length != 0) {
        return true;
      } else {
        return false;
      }
    },
    getStorageCardflag() {
      if (this.StorageCardList.length != 0) {
        return true;
      } else {
        return false;
      }
    },
    addBack() {},
  },
  data() {
    return {
      isLoading: false,
      active: 2,
      //信用卡
      CreditCardList: [],
      //存储卡
      StorageCardList: [],
      tabsName: 0,
    };
  },
  mounted() {
    this.getAllBankCard();
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        this.isLoading = false;
        this.getAllBankCard();
      }, 1000);
    },
    //信用卡
    AddCreditCard() {
      this.$router.push("/addcreditcard");
    },
    // 储存卡
    AddStorageCard() {
      this.$router.push("/addstoragecard");
    },
    tabsAddBank(name, title) {
      this.tabsName = name;
    },
    addBank() {
      if (this.tabsName === 0) {
        this.AddCreditCard();
      } else {
        this.AddStorageCard();
      }
    },

    leftClick() {
      this.$router.back(-1);
    },
    //获取银行卡
    getAllBankCard() {
      let _this = this;
      queryAllBankCardInfoApi(_this.token)
        .then((res) => {
          if (res.resp_code === "000000") {
            _this.CreditCardList = [];
            _this.StorageCardList = [];
            res.result
              .map((item) => {
                queryCardPicApi().then((ress) => {
                  if (ress.resp_code === "000000") {
                    ress.result.map((items) => {
                      if (item.bankName == items.bank_name) {
                        item.background = items.background;
                        item.bank_acronym = items.bank_acronym;
                      }
                    });
                    if (item.nature.indexOf("贷") > -1) {
                      _this.CreditCardList.push(item);
                    }

                    if (item.nature.indexOf("借") > -1) {
                      _this.StorageCardList.push(item);
                    }
                    console.log("_this.CreditCardList:", _this.CreditCardList);
                    console.log(
                      "_this.StorageCardList:",
                      _this.StorageCardList
                    );
                  }
                });
              })

              .catch((err) => {
                console.log(err);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改信用卡
    UpdateCard(item) {
      console.log(item);
      this.$router.push({
        name: "UpdateCreditCard",
        params: {
          userName: item.userName,
          phone: item.phone,
          userId: item.userId,
          bankCardNumber: item.cardNo,
          securityCode: item.securityCode,
          expiredTime: item.expiredTime,
          billDay: item.billDay,
          repaymentDay: item.repaymentDay,
          creditBlance: item.creditBlance,
        },
      });
    },
    // 修改储蓄卡
    UpdateModificationCard(item) {
      this.$router.push({
        name: "UpdateModificationCard",
        params: {
          userId: item.userId,
          bankCardNumber: item.cardNo,
          province: item.province,
          city: item.city,
          realname: item.userName,
          phone: item.phone,
        },
      });
    },
    //del 信用卡
    delCredClick(item) {
      console.log("del 信用卡", item);
      this.$dialog
        .confirm({
          title: "刪除信用卡",
          message:
            "您确定需要删除该银行卡吗?（注意：删除该卡可能导致某些交易失败或未知错误，请谨慎处理）",
        })
        .then(() => {
          queryDelBankCrad(this.token, item.cardNo, 0)
            .then((res) => {
              console.log("delCredClick", res);
              if (res.resp_code == "000000") {
                this.$toast(res.resp_message);
                this.getAllBankCard();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    //刪除儲蓄卡
    delStoragCredClick(item) {
      console.log("del 信用卡", item);
      this.$dialog
        .confirm({
          title: "刪除信用卡",
          message:
            "您确定需要删除该银行卡吗?（注意：删除该卡可能导致某些交易失败或未知错误，请谨慎处理）",
        })
        .then(() => {
          queryDelBankCrad(this.token, item.cardNo, 2)
            .then((res) => {
              console.log("delCredClick", res);
              if (res.resp_code == "000000") {
                this.$toast(res.resp_message);
                this.getAllBankCard();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    //默认卡

    updataMoRen(item) {
      console.log("默认卡", item);
      this.$dialog
        .confirm({
          title: "默认卡",
          message: "您确定该银行卡设为默认卡吗?",
        })
        .then(() => {
          queryModifyDefaultWithdrawalsCardInfoApi(this.token, item.cardNo)
            .then((res) => {
              if (res.resp_code == "000000") {
                this.$toast(res.resp_message);
                this.getAllBankCard();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>
<style scoped>
.van-tabs {
  margin-bottom: 50px;
}
.van-empty {
  margin-top: 20%;
  display: flex;
  justify-items: center;
  text-align: center;
  font-size: 14px;
  color: #999;
  line-height: 25px;
}
.addCredit {
  margin: 5px auto;
  width: 120px;
  border-radius: 18px;
  border: 1px solid #eee;
  background-color: #fff;
  padding-top: 3px;
  padding-bottom: 3px;
}
.bank {
  width: 345px;
  height: 170px;
  margin: 12px auto;
  border-radius: 8px;
  padding: 15px 15px 13px 16px;
  color: #fff;
  font-size: 14px;
}
.bank-main {
  display: flex;
}
.bankCrad {
  flex: 1;
  margin-left: 12px;
}
.bank_name {
  font-size: 17px;
}
.bank_name span {
  margin-left: 8px;
  font-size: 14px;
}
.bank-type {
  margin-top: 5px;
  font-size: 13px;
  margin-bottom: 20px;
}
.bankCradId {
  font-size: 18px;
  line-height: 25px;
}
.bank-up {
  margin-top: 20px;
  border-top: 1px solid #fff;
  padding-top: 12px;
  display: flex;
  align-items: center;
}
.bank-up p {
  flex: 1;
  font-size: 14px;
}
.bank-up div {
  display: flex;
  align-items: center;
  margin-left: 5px;
  margin-right: 8px;
}
.bank-up div img {
  margin-right: 3px;
}
.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1.33333rem;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
}
.footer span {
  margin-left: 3px;
}
.van-image {
  padding: 1px;
  background-color: #fff;
  box-sizing: border-box;
}
.setCradka {
  height: 22px;
  padding: 5px 10px;
  border: 1px solid #fff;
  border-radius: 15px;
  font-size: 12px;
}
</style>